package cn.pconline.autoclub.util.ubb.node;

import cn.pconline.autoclub.util.ubb.EscapeUtils;
import cn.pconline.autoclub.util.ubb.Node;



public class UrlNodeMobile extends AbstractNode {


    public UrlNodeMobile() {
    }

    private UrlNodeMobile(String name, String attribute) {
        super.name = name;
        super.attribute = attribute;
    }


    @Override
    public StringBuilder getText(java.util.LinkedList<Node> stack) {
        StringBuilder sb = new StringBuilder();

        sb.append("<a href=\"");
        String url = text.toString();

        if (attribute != null) {
            attribute = replaceUrl(attribute.trim());
            EscapeUtils.appendAttribute(attribute, sb);
        } else {
            attribute = url;
            sb.append(attribute);
        }
        if(attribute.contains("pcautobrowser") || attribute.contains("pconlinebrowser")){
        	sb.append("\" class=\"underline\">").append(url).append("</a> ");
        }else{
        	 sb.append("\">").append(url).append("</a> ");
        }


        return sb;
    }

    @Override
    public void appendText(CharSequence text) {
        if (attribute == null) {
            EscapeUtils.appendAttribute(text, super.text);
        } else {
            EscapeUtils.appendHtml(text, super.text);
        }
    }

    @Override
    public Node copyWithoutText() {
    	UrlNodeMobile result = new UrlNodeMobile(name, attribute);
        return result;
    }

    @Override
    public Node build(String name, String attribute) {
    	UrlNodeMobile result = new UrlNodeMobile(name, attribute);
        return result;
    }

    private String replaceUrl(String url) {
    	//移动端接口，列表页链接和帖子页链接作出如下规则替换
        if (url.indexOf("http://bbs.pcauto.com.cn/forum-") != -1) {
        	url = url.replace("http://bbs.pcauto.com.cn/forum-", "pcautobrowser://bbs-topics/");
        	url = url.replace(".html", "");
        }
        if (url.indexOf("http://bbs.pcauto.com.cn/topic-") != -1) {
        	url = url.replace("http://bbs.pcauto.com.cn/topic-", "pcautobrowser://bbs-topic/");
        	url = url.replace(".html", "");
        }
        if (url.indexOf("http://itbbs.pconline.com.cn/f-") != -1) {
        	url = url.replace("http://itbbs.pconline.com.cn/f-", "pconlinebrowser://bbs-topics/");
        	url = url.replace(".html", "");
        }
        if (url.indexOf("http://itbbs.pconline.com.cn/") != -1) {
        	String topicId =url.replace("http://itbbs.pconline.com.cn/","").replace(".html", "");
        	if(isNum(topicId)){
        		url = url.replace("http://itbbs.pconline.com.cn/", "pconlinebrowser://bbs-topic/");
            	url = url.replace(".html", "");
        	}
        }

        return url;
    }

    private boolean isNum(String num){
    	boolean result = true;
    	try{
    		Long.parseLong(num);
    	}catch(Exception e){
    		result = false;
    	}
    	return result;
    }
}
